package com.all.security.service;

import com.all.security.model.request.LoginRequest;
import com.all.security.model.vo.LoginVO;
import com.all.security.utils.BeanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author
 * @ClassName LoginService
 * @Date 2024/3/31 17:16
 * @Description 登陆service
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
public class LoginService {

    private final AuthenticationManager authenticationManager;

    public LoginVO doLogin(LoginRequest loginRequest){
        Authentication authenticationRequest =
                UsernamePasswordAuthenticationToken.unauthenticated(loginRequest.getUsername(), loginRequest.getPassword());
        Authentication authenticationResponse =
                this.authenticationManager.authenticate(authenticationRequest);
        Collection<? extends GrantedAuthority> authorities = authenticationResponse.getAuthorities();
        LoginVO loginVO = BeanUtils.copyProperties(authenticationResponse.getPrincipal(), LoginVO.class);
        List<String> roles = new ArrayList<>();
        authorities.forEach(r -> roles.add(r.toString()));
        loginVO.setRoles(roles);
        return loginVO;
    }
}
